
package controllers;

import play.db.jpa.Transactional;
import play.mvc.Result;

public class Asset extends Application {

    public static Result index() {
        return ok();
    }

    @Transactional
    public static Result view(final Long id) {
    	if(Authentication.isAdmin()) {
	        models.aaa.Asset item = models.aaa.Asset.find.byId(id);
	        if (item == null) {
	            return notFound(views.html.error.notFound.render(""));
	        }
	        models.aaa.Asset actor = getUser().getActor();
	        if (!item.access().isAllowed(actor)) {
	            //return forbidden(views.html.error.forbidden.render(""));
	        }
	        //System.out.println(item.)
	        return ok(views.html.asset.view.render(item));
		}
		return forbidden();
    }
    
    @Transactional
    public static Result redirect(final String user, final Long id) {
        models.aaa.Asset item = models.aaa.Asset.find.byId(id);
        if (item == null) {
            return notFound(views.html.error.notFound.render(""));
        }
        
        models.aaa.Asset actor = new models.aaa.Asset();
        if (user != null) {
            actor = models.aaa.Asset.find.byIdentifier("pid", user);
        } else {
            actor = getUser().getActor();
        }
        
//        if (!item.access().isAllowed(actor)) { // TODO à décommenter pour les vrais permissions
//            return forbidden(views.html.error.forbidden.render(""));
//        }
        for (models.aaa.Resource res : item.getResources()) {
//            Logger.info("-------------- redirect URL ="+res.getAbout());
            return redirect(res.getAbout().toString());
        }
        return ok(views.html.asset.view.render(item));
    }

}
